import React, { Component } from "react";
import { Form, Input, Select } from "antd";
import PropTypes from "prop-types";
//添加form组件
const Item = Form.Item;
const Option = Select.Option;
export default class UserForm extends Component {
  static propTypes = {
    setForm: PropTypes.func.isRequired,
    roles: PropTypes.array.isRequired,
    user: PropTypes.object,
    roleNames: PropTypes.array,
  };
  constructor(props) {
    super(props);
    this.formRef = React.createRef();
  }
  render() {
    const { roles } = this.props;
    const user = this.props.user || {};
    const roleNames = this.props.roleNames || [];
    console.log("999999999999999999", user);
    this.props.setForm(this.formRef);
    return (
      <Form onFinish={this.onFinish} ref={this.formRef}>
        <Item
          label="用户"
          name="username"
          // 声明式验证
          rules={[
            { required: true, whitespace: true, message: "请输入用户名!" },
            { min: 4, message: "长度不小于4" },
            { max: 12, message: "长度不大于12" },
            {
              pattern: /^[a-zA-Z0-9_]+$/,
              message: "用户名必须是英文字母或下划线",
            }, //正则表达式
          ]}
        >
          <Input
            placeholder="输入用户名"
            key={user.username}
            defaultValue={user.username}
          />
        </Item>
        {user.id ? null : (
          <Item
            label="密码"
            name="password"
            rules={[
              { required: true, message: "请输入密码!" },
              { min: 4, message: "密码不小于4" },
              {
                pattern: /^[a-zA-Z0-9_]+$/,
                message: "密码必须是英文字母或下划线",
              }, //正则表达式
            ]}
          >
            <Input
              type="password"
              placeholder="输入密码"
              key={user.password}
              defaultValue={user.password}
            />
          </Item>
        )}

        <Item label="电话" name="phone">
          <Input
            placeholder="输入手机号"
            key={user.phone}
            defaultValue={user.phone}
          />
        </Item>
        <Item label="邮箱" name="email">
          <Input
            placeholder="输入邮箱"
            defaultValue={user.email}
            key={user.email}
          />
        </Item>
        <Item label="角色" name="roleId">
          <Select
            placeholder="选择角色"
            defaultValue={roleNames[user.roleId]}
            key={roleNames[user.roleId]}
          >
            {roles.map((role) => (
              <Option key={role.id} value={role.name}>
                {role.name}
              </Option>
            ))}
          </Select>
        </Item>
      </Form>
    );
  }
}
